package com.wu.webstep4.customUrl;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	private final AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	private final Map<String,String> map = new HashMap<String, String>();
	
	public MyFilterInvocationSecurityMetadataSource() {
		map.put("/hello", "ROLE_USER");
		map.put("/index", "whiter");
		map.put("/js/**", "whiter");
		
		
	}
	
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		FilterInvocation fi = (FilterInvocation) object;
		//获取用户请求的Url
		String url = fi.getRequestUrl();
		for (Map.Entry<String, String> entry: map.entrySet()) {
			if(antPathMatcher.match(entry.getKey(), url)) {
				if("whiter".equals(map.get(entry.getKey()))) {
					//所有人都可以访问，返回null即可，返回null则不会进入之后的decide方法
					return null;
				}
				return SecurityConfig.createList(entry.getValue());
			}
		}
		return SecurityConfig.createList("ROLE_USER");
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return FilterInvocation.class.isAssignableFrom(clazz);
	}

}
